package com.isoftstone.demo.web;

import com.github.pagehelper.PageInfo;
import com.isoftstone.demo.OrderQuery;
import com.isoftstone.demo.common.OrderVO;
import com.isoftstone.demo.common.utils.CommonUtils;
import com.isoftstone.demo.pojo.Order;
import com.isoftstone.demo.service.IOrderService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author: 于浩强
 **/
@Controller
@RequestMapping
public class PurchaseOrderController {
    @Resource
    private IOrderService orderService;

    @GetMapping("/purchaseOrder")
    public String show(OrderQuery query, Model model) {
        PageInfo<Order> page = orderService.listOrderByPage(query.getPage(), query.getPageSize());
        List<OrderVO> orderVOS = page.getList().stream().map(order -> {
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(order, orderVO);

            orderVO.setStringdate(CommonUtils.toDateString(order.getOrderdate().getTime()));
            return orderVO;
        }).collect(Collectors.toList());

        PageInfo<OrderVO> of = PageInfo.of(orderVOS);
        of.setTotal(page.getTotal());
        of.setPages(page.getPages());
        of.setPageNum(page.getPageNum());

        model.addAttribute("page", of);
        model.addAttribute("pvo", query);
        return "purchaseOrder/index";
    }

    @RequestMapping("/purchaseOrder/del")
    @ResponseBody
    public Integer del(Integer id) {
        if (Objects.isNull(id)) {
            return 0;
        } else {
//            orderService.deleteOrder(id);
            return 1;
        }
    }

    @RequestMapping("/purchaseOrder/{id}")
    public String toUpdate(@PathVariable("id") int id, Model model) {
        Order order = orderService.getById(id);
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(order, orderVO);

        orderVO.setStringdate(CommonUtils.toDateString(order.getOrderdate().getTime()));
        model.addAttribute("order", orderVO);
        return "purchaseOrder/update";
    }

    @RequestMapping("/purchaseOrder/update")
    public String update(OrderVO vo) {
        orderService.updateOrder(vo);

        return "redirect:/purchaseOrder/"+vo.getOid();
    }
}
